package com.wrx.club_management_backend.controller;

import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.dto.ApproveClubDTO;
import com.wrx.club_management_backend.dto.JoinClubDTO;
import com.wrx.club_management_backend.entity.Club;
import com.wrx.club_management_backend.mapper.ClubMapper;
import com.wrx.club_management_backend.service.ClubService;
import com.wrx.club_management_backend.utils.RedisCacheWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wrx.club_management_backend.utils.RedisConstant.CACHE_CLUB;
import static com.wrx.club_management_backend.utils.RedisConstant.CACHE_TTL;

@RestController
@RequestMapping("/club")
public class ClubController {
    @Autowired
    private ClubService clubService;

    /**
     * 查询社团数量
     * @return 社团数量
     */
    @GetMapping("/num")
    public AjaxResult num(){
        return clubService.num();
    }


    //==============社团收藏相关接口=====================
    @PostMapping("collected/{clubId}")
    public AjaxResult collected(@PathVariable("clubId") Long clubId) {
        return clubService.collected(clubId);
    }

    @PostMapping("isCollected/{clubId}")
    public AjaxResult isCollected(@PathVariable("clubId") Long clubId) {
        return clubService.isCollected(clubId);
    }

    @PostMapping("/collectedNum/{clubId}")
    public AjaxResult collectedNum(@PathVariable("clubId") Long clubId) {
        return clubService.collectedNum(clubId);
    }
    //==================================================


    // ================加入社团-移除社团================
    @PostMapping("/join")
    public AjaxResult joinClub(@RequestBody JoinClubDTO dto) {
        return clubService.joinClub(dto.getClubId(), dto.getUserId());
    }
    @PostMapping("removeUser/{userId}/{clubId}")
    public AjaxResult removeUser(@PathVariable("userId") Long userId,
                                 @PathVariable("clubId") Long clubId) {
        clubService.removeUser(userId, clubId);
        return AjaxResult.success("剔除成功");
    }
    // =================================================






    @GetMapping("/hot")
    public AjaxResult hot() {
        return clubService.hot();
    }

    // 保留原有的list方法
    @GetMapping("/list")
    public AjaxResult list( ) {
        List<Club> list = clubService.list();
        return AjaxResult.success(list);
    }

    /**
     * 获取当前用户参加的社团
     *
     * @return
     */
    @GetMapping
    public AjaxResult get() {
        return clubService.get();
    }

    // 获取社团详情
    @GetMapping("/detail/{id}")
    public AjaxResult getClubDetail(@PathVariable Long id) {
        return clubService.getClubDetail(id);
    }

    // 获取社团活动列表
    @GetMapping("/activities/{clubId}")
    public AjaxResult getClubActivities(@PathVariable Long clubId) {
        return clubService.getClubActivities(clubId);
    }

    // 获取社团成员列表
    @GetMapping("/members/{clubId}")
    public AjaxResult getClubMembers(@PathVariable Long clubId) {
        return clubService.getClubMembers(clubId);
    }


    // 获取社团荣誉列表
    @GetMapping("/achievements/{clubId}")
    public AjaxResult getClubAchievements(@PathVariable Long clubId) {
        return clubService.getClubAchievements(clubId);
    }

    // 更新收藏状态
    @PostMapping("/favorite")
    public AjaxResult updateFavorite(@RequestParam Long clubId,
                                     @RequestParam Long userId,
                                     @RequestParam Boolean isFavorite) {
        return clubService.updateFavorite(clubId, userId, isFavorite);
    }

    // 活动报名
    @PostMapping("/activity/signup")
    public AjaxResult signupActivity(@RequestParam Long activityId,
                                     @RequestParam Long userId) {
        return clubService.signupActivity(activityId, userId);
    }


    // 退出社团
    @PostMapping("/quit")
    public AjaxResult quitClub(@RequestParam Long clubId,
                               @RequestParam Long userId) {
        return clubService.quitClub(clubId, userId);
    }

    // 任命管理层
    @PostMapping("/manager/appoint")
    public AjaxResult appointManager(@RequestParam Long clubId,
                                     @RequestParam Long userId,
                                     @RequestParam String position,
                                     @RequestParam String department) {
        return clubService.appointManager(clubId, userId, position, department);
    }

    // 解除管理层职务
    @PostMapping("/manager/dismiss")
    public AjaxResult dismissManager(@RequestParam Long clubId,
                                     @RequestParam Long userId,
                                     @RequestParam String position) {
        return clubService.dismissManager(clubId, userId, position);
    }

    @GetMapping("/president/{clubId}")
    public AjaxResult getClubPresident(@PathVariable Long clubId) {
        return clubService.getClubPresident(clubId);
    }

    @GetMapping("/managed")
    public AjaxResult getManagedClubs(@RequestParam(required = false) Long userId) {
        return clubService.getManagedClubs(userId);
    }

    @PostMapping("/updateStat/{clubId}/{recruit}")
    public AjaxResult updateStat(@PathVariable("clubId") Long clubId, @PathVariable("recruit") int recruit) {
        return clubService.updateStat(clubId, recruit);
    }





    // 创建社团
    @PostMapping("/create")
    public AjaxResult create(@RequestBody Club club){
        return this.clubService.create(club);
    }
    // 获取审批社团列表
    @PostMapping("/approveList")
    public AjaxResult getApproveList(){
        return clubService.getApproveList();
    }
    // 对社团进行审批
    @PostMapping("/approve")
    public AjaxResult approve(@RequestBody ApproveClubDTO dto){
        return clubService.approve(dto);
    }
    @PostMapping("search")
    public AjaxResult search(@RequestBody ApproveClubDTO dto){
        return clubService.search(dto);
    }

    @Autowired
    RedisCacheWorker redisCacheWorker;


    @PostMapping("/info/{clubId}")
    public AjaxResult info(@PathVariable("clubId") Long clubId){
        Club club = redisCacheWorker.queryWithPassThrough(
                clubId,
                CACHE_CLUB,
                CACHE_TTL,
                TimeUnit.MINUTES,
                Club.class,
                clubService::getById
        );
        return AjaxResult.success(club);
    }


    @Autowired
    ClubMapper clubMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @PostMapping("/membersWithPermissions/{clubId}/{permissions}")
    public AjaxResult listMembersWithPermissions(@PathVariable("clubId") Long clubId, @PathVariable("permissions") String permissions ){
        List<Map<String, Object>> maps = clubMapper.selectClubMembers(clubId);
        String key = "club:" + permissions +":" + clubId;
        System.out.println(key);
        for (Map<String, Object> map : maps) {
            Long userId =(Long) map.get("id");
            Boolean flag  = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
            map.put(permissions, flag);
        }
        return AjaxResult.success(maps);
    }

    // 更新用户权限
    @PostMapping("/updatePermissions/{clubId}/{userId}/{permissions}/{stat}")
    public AjaxResult updatePermissions(
            @PathVariable("clubId") Long clubId,
            @PathVariable("userId") Long userId,
            @PathVariable("permissions") String permissions,
            @PathVariable("stat") int stat

    ){
        String key = "club:" + permissions + ":" + clubId;
        if(stat == 1){ // 添加权限
            stringRedisTemplate.opsForSet().add(key, userId.toString());
        }else{ // 剥夺权限
            stringRedisTemplate.opsForSet().remove(key, userId.toString());
        }
        return AjaxResult.success("权限修改完成");
    }

    // 查看某个用户的权限是否存在
    @PostMapping("select/{userId}/{clubId}/{permissions}")
    public AjaxResult selectWithPermissions(
            @PathVariable("userId") Long userId,
            @PathVariable("clubId") Long clubId,
            @PathVariable("permissions") String permissions ){
        String key = "club:" + permissions + ":" + clubId;

        Boolean flag = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        return AjaxResult.success(flag);
    }

}
